package org.chen.wordwave.Api;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import androidx.annotation.NonNull;

import org.chen.wordwave.tools.token.TokenUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

public class AuthInterceptor implements Interceptor {
    private SharedPreferences sharedPreferences;

    public AuthInterceptor(Context context) {
        this.sharedPreferences = context.getSharedPreferences("APP_PREFS", Context.MODE_PRIVATE);
    }

    @NonNull
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        String session = sharedPreferences.getString("SESSION", "chen88.top");
        Request originalRequest = chain.request();

        // 只有当请求体不为空时才进行加密
        if (originalRequest.body() != null) {
            // 读取请求体内容
            Buffer buffer = new Buffer();
            originalRequest.body().writeTo(buffer);
            byte[] bytes = buffer.readByteArray();

            // 加密内容
            String encryptedContent = "";
            try {
                encryptedContent = TokenUtils.encrypt(bytes);
            } catch (Exception e) {
                Log.e("e",e.toString());
                // 处理加密错误
            }

            // 创建加密后的请求体
            RequestBody encryptedRequestBody = RequestBody.create(
                    encryptedContent,
                    MediaType.parse("application/json"));

            // 创建新的请求，并替换原始请求体
            Request newRequest = originalRequest.newBuilder()
                    .method(originalRequest.method(), encryptedRequestBody)
                    .header("Cookie", session)
                    .build();

            return chain.proceed(newRequest);
        }

        return chain.proceed(originalRequest);
    }
}
